﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using NPOI;
using NPOI.HSSF;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;

namespace RenShiKaoQin.Bussiness
{
    public class ExcelHelper
    {
        public static void GridViewtoExcel(GridView gv, string fileName)
        {
            IWorkbook wb = new HSSFWorkbook();
            ISheet sheet = wb.CreateSheet("假期汇总");
            IRow hRow = sheet.CreateRow(0);
            int i = 0;
            foreach (TableCell cell in gv.HeaderRow.Cells)
            {
                hRow.CreateCell(i).SetCellValue(cell.Text);
                i++;
            }
            foreach (GridViewRow gvRow in gv.Rows)
            {
                IRow row = sheet.CreateRow(gvRow.RowIndex + 1);
                int cIndex = 0;
                foreach (TableCell gvCell in gvRow.Cells)
                {
                    row.CreateCell(cIndex).SetCellValue(gvCell.Text);
                    cIndex++;
                }
            }
            using (MemoryStream ms = new MemoryStream())
            {
                wb.Write(ms);
                byte[] data = ms.ToArray();
                HttpResponse response = System.Web.HttpContext.Current.Response;
                response.Clear();
                response.Charset = "UTF-8";
                response.ContentType = "application/vnd-excel";
                response.AddHeader("Content-Disposition", string.Format("attachment; filename="+fileName));
                response.BinaryWrite(data);
                response.End();
            }
        }
    }
}